import { Component, Input, ViewChild, ElementRef, OnInit } from '@angular/core';
import { FileUploader, FileItem, ParsedResponseHeaders } from 'ng2-file-upload';
import { OnShowMore } from 'app/ibizsys/interface/OnShowMore';
import { OnNew } from 'app/ibizsys/interface/OnNew';
import { IBizNotification } from '@ibizsys/util/IBizNotification';
import { IBizEnvironment } from '@env/IBizEnvironment';

@Component({
    selector: 'app-ibiz-file-upload',
    templateUrl: './ibiz-file-upload.component.html',
    styleUrls: ['./ibiz-file-upload.component.less']
})
export class IBizFileUploadComponent implements OnInit, OnShowMore, OnNew {

	/**
	 * 上传插件对象
	 * 
	 * @type {FileUploader}
	 * @memberof IBizFileUploadComponent
	 */
    public uploader: FileUploader;

	/**
	 * 已上传文件对象集合
	 * 
	 * @type {any[]}
	 * @memberof IBizFileUploadComponent
	 */
    public files: any[] = [];

	/**
	 * 控件扩展菜单对象集合
	 * 
	 * @memberof IBizFileUploadComponent
	 */
    public actions = [{ text: '按名称排序', value: 'name', sortdir: 1, menuIndex: 1, check: true }];

	/**
	 * 控件样式对象
	 * 
	 * @type {*}
	 * @memberof IBizFileUploadComponent
	 */
    @Input()
    public styleCss: any = {};

    @Input()
    form: any;
    @Input()
    name: string;
    @Input()
    disabled: boolean;
    @Input()
    groupname: string;
    @Input()
    set itemvalue(val) {
        if (val) {
            if (typeof val === 'string') {
                try {
                    this.files = JSON.parse(val);
                } catch (error) {
                    console.log('string to json error');
                }
            } else {
                this.files = val;
            }
        } else {
            this.files = [];
        }
    }

    /**
     * 编辑器附加参数
     *
     * @memberof IBizFileUploadComponent
     */
    @Input()
    params: any;

    /**
     *文件上传dom对象
     *
     * @type {ElementRef}
     * @memberof IBizFileUploadComponent
     */
    @ViewChild('fileUpload')
    fileUpload: ElementRef;

    /**
     * 文件上传状态
     *
     * @type {boolean}
     * @memberof IBizFileUploadComponent
     */
    public _isSpinning: boolean = false;

    constructor(
        private iBizNotification: IBizNotification,
    ) {
        let url = IBizEnvironment.UploadFile + '?';
        url = (IBizEnvironment.LocalDeve ? '' : '..') + url;
        this.uploader = new FileUploader({
            // url: url,
            autoUpload: true
        });
        // 文件上传之前上传地址处理
        this.uploader.onBeforeUploadItem = (fileitem: FileItem) => {
            this._isSpinning = true;
            let uploadUrl = url;
            if (this.form && this.params && this.params.uploadparams && !Object.is(this.params.uploadparams, '')) {
                let fields: string[] = this.params.uploadparams.split(';');
                fields.forEach((item) => {
                    let fieldItem = this.form.findField(item);
                    if (fieldItem) {
                        uploadUrl += '&' + item + '=' + fieldItem.value;
                    }
                });
            }
            if (this.form && this.params && typeof this.params.customparams === 'object') {
                const _names: Array<any> = Object.keys(this.params.customparams);
                _names.forEach((key) => {
                    uploadUrl += '&' + key + '=' + this.params.customparams[key];
                });
            }
            this.uploader.setOptions({
                url: uploadUrl
            });
        };
        // 文件上传成功回调
        this.uploader.onSuccessItem = (item, response, status, headers) => {
            this._isSpinning = false;
            this.successItem(item, response, status, headers);
        };
        // 文件上传失败回调
        this.uploader.onErrorItem = (item, response, status, headers) => {
            this._isSpinning = false;
            this.iBizNotification.error('错误', '系统异常！');
        };
    }

    ngOnInit() {
        if (this.form) {
            let groupField = this.form.findField(this.groupname);
            if (groupField && Object.is(groupField.getFieldType(), 'GROUPPANEL')) {
                groupField.regEditor(this.name, this);
            }
        }
    }

    /**
   * 删除上传的文件
   * 
   * @param {any} file 
   * @memberof IBizFileUploadComponent
   */
    public clearFile(file): void {
        this.files.forEach((item, index) => {
            if (file.id === item.id) {
                this.files.splice(index, 1);
            }
        });
        this.setValue();
    }

	/**
	 * 上传文件成功返回
	 * 
	 * @param {FileItem} item 
	 * @param {string} response 
	 * @param {number} status 
	 * @param {ParsedResponseHeaders} headers 
	 * @returns {*} 
	 * @memberof IBizFileUploadComponent
	 */
    public successItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
        let res: any = JSON.parse(response);
        if (res && res.ret === 0) {
            if (res.success) {
                this.files.push(...res.files);
                this.setValue();
            } else {
                this.iBizNotification.error('错误', res.errorMessage);
            }
        } else {
            this.iBizNotification.error('错误', res.errorMessage);
        }
    }

	/**
	 * 设置选中值
	 *
	 * @memberof IBizFileUploadComponent
	 */
    public setValue(): void {
        if (this.form) {
            let itemField = this.form.findField(this.name);
            if (itemField) {
                itemField.setValue(JSON.stringify(this.files));
            }
        }
    }

	/**
	 * 执行控件自带扩展功能
	 * 
	 * @param {*} action 
	 * @memberof IBizFileUploadComponent
	 */
    public doMoreAction(action: any): void {
        switch (action.menuIndex) {
            case 1: this.sortFile(action); break;
            default: break;
        }
    }

	/**
	 * 触发上传功能
	 * 
	 * @memberof IBizFileUploadComponent
	 */
    public doNewAction(): void {
        this.fileUpload.nativeElement.click();
    }

	/**
	 * 已上传文件排序
	 * 
	 * @param {*} action 
	 * @memberof IBizFileUploadComponent
	 */
    public sortFile(action: any): void {
        action.sortdir = -action.sortdir;
        this.files = this.files.sort((file1, file2) => {
            if (file1[action.value] > file2[action.value]) {
                return -action.sortdir;
            } else if (file1[action.value] < file2[action.value]) {
                return action.sortdir;
            } else {
                return 0;
            }
        });
    }

	/**
	 * 获取控件扩展功能菜单
	 * 
	 * @returns {any[]} 
	 * @memberof IBizFileUploadComponent
	 */
    public getMoreActions(): any[] {
        return this.actions;
    }

	/**
	 * 下载文件
	 * 
	 * @param {*} file 
	 * @memberof IBizFileUploadComponent
	 */
    public downFile(file: any) {
        let url = IBizEnvironment.ExportFile + '?fileid=' + file.id;
        url = (IBizEnvironment.LocalDeve ? '' : '..') + url;
        if (this.form && this.params && this.params.exportparams && !Object.is(this.params.exportparams, '')) {
            let fields: string[] = this.params.exportparams.split(';');
            fields.forEach((item) => {
                let fieldItem = this.form.findField(item);
                if (fieldItem) {
                    url += '&' + item + '=' + fieldItem.value;
                }
            });
        }
        if (this.form && this.params && typeof this.params.customparams === 'object') {
            const _names: Array<any> = Object.keys(this.params.customparams);
            _names.forEach((key) => {
                url += '&' + key + '=' + this.params.customparams[key];
            });
        }
        window.open(url);
    }
}


